package com.yhs.YShop.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yhs.YShop.common.utils.R;
import com.yhs.YShop.model.Operation;
import com.yhs.YShop.pojo.Menu;
import com.yhs.YShop.service.OperationService;

@RestController
@RequestMapping("operation")
/**
 * @CrossOrigin 描述方法，代表只有当前方法支持跨域访问。粒度最细致。建议使用。 可以使用注解属性来配置更加详细的Cros协议参数配置。
 *              allowedHeaders - 请求头是否携带。 外部域发送到当前方法的请求头是否转交给当前方法。
 *              allowCredentials - 是否支持外部用户凭证，用于处理oauth2.0的。 methods - 支持的请求类型。
 * @return
 */

public class OperationController {

	@Autowired
	private OperationService operationService;

	@RequestMapping("selectOperation")
	public R selectOperation() {

		Map<Integer, Operation> map = new HashMap<Integer, Operation>();
		Map<Integer, List<Operation>> firstMap = new HashMap<Integer, List<Operation>>();
		Map<String, List<Menu>> senendMap = new HashMap<String, List<Menu>>();
		List<Operation> operations = operationService.findAll();
		if (operations != null && operations.size() > 0) {
			for (Operation operation : operations) {
				operation.setCode(operation.getCode().toLowerCase());
				if (operation.getId().equals(2) || !operation.getPermType().equals(1)) {
					continue;
				}
				// 顶级菜单
				if (operation.getParentMenuId().equals(2) && operation.getPermType().equals(1)) {
					map.put(operation.getId(), operation);
				} else {
					// 第一子集
						List<Operation> muList = firstMap.get(operation.getParentMenuId());
						if (muList == null) {
							muList = new ArrayList<Operation>();
						}
						muList.add(operation);
						firstMap.put(operation.getParentMenuId(), muList);
				}

			}
		}
		// 开始，循环数据信息
		for (Integer parentId : map.keySet()) {
			List<Operation> childOperations = firstMap.get(parentId);
			if (childOperations != null) {
				// 判断有没有第二子集
				childOperations.forEach(s -> {
					List<Operation> seList = firstMap.get(s.getId());
					if (seList != null) {
						s.setChildOperations(seList);
					}
				});
				Operation operation = map.get(parentId);
				operation.setChildOperations(childOperations);

			}
		}

		return R.ok(map.values());
	}
}
